package com.supermarket.controller;

import com.supermarket.entity.User;
import com.supermarket.service.UserService;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@CrossOrigin(
        origins = "http://localhost:8081",
        allowCredentials = "true",
        methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS }
)
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getById(id);
    }

    @GetMapping("/getUserCode/{getUserCode}")
    public User getByUserCode(@PathVariable String getUserCode) {
        return userService.getByUserCode(getUserCode);
    }

    @GetMapping("/all")
    public List<User> getAll() {
        return userService.getAll();
    }
    
    @GetMapping("/list")
    public R<Object> list(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String userCode,
            @RequestParam(required = false) String userName) {
        return userService.getUserList(currentPage, pageSize, userCode, userName);
    }

    @PostMapping
    public R<String> createUser(@RequestBody User user) {
        try {
            // 检查用户编码是否已存在
            if (userService.getByUserCode(user.getUserCode()) != null) {
                return R.createError(StatusCode.ERROR, "用户编码已存在");
            }

            // 设置默认状态
            if(user.getStatus() == null) {
                user.setStatus(1); // 默认启用
            }

            // 设置创建时间
            user.setCreationDate(new Date(TimeZone.getTimeZone("UTC").getOffset(System.currentTimeMillis()) + System.currentTimeMillis()));

            // 保存用户
            userService.create(user);
            return R.createSuccess("用户添加成功");
        } catch (Exception e) {
            e.printStackTrace(); // 添加异常打印，便于调试
            return R.createError(StatusCode.ERROR, "添加用户失败: " + e.getMessage());
        }
    }

    @PutMapping
    public R<User> updateUser(@RequestBody User user) {
        try {
            if (user.getId() == null) {
                return R.createError(StatusCode.ERROR, "缺少用户 ID");
            }
            
            // 1. 先查出数据库中完整的对象
            User existing = userService.getById(user.getId());
            if (existing == null) {
                return R.createError(StatusCode.ERROR, "用户不存在");
            }
            
            // 2. 判断是否是状态更新（只传了id和status）
            if (user.getStatus() != null && user.getUserName() == null) {
                // 这是状态更新请求
                existing.setStatus(user.getStatus());
                System.out.println("更新用户状态: ID=" + user.getId() + ", 新状态=" + user.getStatus());
            } else {
                // 这是完整信息更新请求
                if (user.getUserName() != null) existing.setUserName(user.getUserName());
                if (user.getGender() != null) existing.setGender(user.getGender());
                if (user.getBirthday() != null) existing.setBirthday(user.getBirthday());
                if (user.getPhone() != null) existing.setPhone(user.getPhone());
                if (user.getAddress() != null) existing.setAddress(user.getAddress());
                if (user.getHeadUrl() != null) existing.setHeadUrl(user.getHeadUrl());
                // 在完整更新时，如果传了status也要更新
                if (user.getStatus() != null) existing.setStatus(user.getStatus());
            }
            
            // 3. 执行更新
            userService.update(existing);
            
            // 4. 返回成功
            String message = user.getStatus() != null && user.getUserName() == null ? 
                    "用户状态更新成功" : "用户信息更新成功";
            R<User> result = R.createSuccess(existing);
            result.setMessage(message);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "更新用户失败: " + e.getMessage());
        }
    }



    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.delete(id);
    }
    @PostMapping("/login")
    public R<User> login(@RequestParam String userCode, @RequestParam String passWord){
        System.out.println("接收登录请求 - userCode: " + userCode + ", passWord长度: " + (passWord != null ? passWord.length() : 0));
        User loginUser = userService.login(userCode, passWord);
        // 获取当前HttpSession
        javax.servlet.http.HttpSession session = org.springframework.web.context.request.RequestContextHolder.getRequestAttributes() instanceof org.springframework.web.context.request.ServletRequestAttributes
                ? ((org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest().getSession()
                : null;
        if(null != loginUser){
            if(loginUser.getStatus() == 1){
                //登录成功，保存用户id到session
                if(session != null) {
                    session.setAttribute("userId", loginUser.getId());
                }
                return R.createSuccess(loginUser);
            }else{
                //登录失败,账号被冻结
                return R.createError(StatusCode.ERROR,"登录失败,账号被冻结,请联系管理员");
            }
        }else{
            //登录失败,用户名和密码错误
            return R.createError(StatusCode.ERROR,"登录失败,用户名或密码错误");
        }
    }

    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file, javax.servlet.http.HttpSession session) {
        try {
            String uploadDir = System.getProperty("user.dir") + "/src/main/resources/static/img/";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();
            String filename = file.getOriginalFilename();
            // 保存文件到服务器
            File dest = new File(uploadDir + filename);
            file.transferTo(dest);
            // 从session获取用户id
            Long id = (Long) session.getAttribute("userId");
            String headUrl = "/img/" + filename;
            userService.updateUserImage(id, headUrl);
            return R.createSuccess(headUrl);
        } catch (Exception e) {
            return R.createError(StatusCode.ERROR, "上传失败：" + e);
        }
    }

    @PostMapping("/updatePassword")
    public R<String> updatePassword(@RequestParam Long userId, 
                                   @RequestParam String oldPassword, 
                                   @RequestParam String newPassword) {
        return userService.updatePassword(userId, oldPassword, newPassword);
    }



}
